package com.grape.rabbitmq.queue.core.topic;

import com.grape.rabbitmq.queue.util.MQConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 描述:发布订阅模式邮件消费者
 * @author: myx
 * @date: 2019-04-30
 * Copyright © 2019-grape. All rights reserved.
 */
public class TopicConsumerEmailFanout {

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("邮件消费者启动");
        // 1.创建新的连接
        Connection connection = MQConnectionUtils.newConnection(TopicConstant.VIRTUALHOST_NAME);
        // 2.创建通道
        Channel channel = connection.createChannel();
        // 3.消费者关联队列
        channel.queueDeclare(TopicConstant.QUEUE_EMAIL_NAME, false, false, false, null);
        // 4.消费者绑定交换机 参数1 队列 参数2交换机 参数3 routingKey
        channel.queueBind(TopicConstant.QUEUE_EMAIL_NAME, TopicConstant.EXCHANGE_NAME, "info.#");
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("消费者获取生产者消息:" + msg);
            }
        };
        // 5.消费者监听队列消息
        channel.basicConsume(TopicConstant.QUEUE_EMAIL_NAME, true, consumer);
    }
}
